/**
 * 账户设置页面
 */
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/pages/my/controller/statement_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import '../../../components/common/text_arrow_item.dart';
import '../../bags/controller/bags_ctr.dart';
import '../../home/controller/home_ctr.dart';

class Settings extends StatefulWidget {
  const Settings({super.key});

  @override
  State<Settings> createState() => _SettingsState();
}

class _SettingsState extends State<Settings> {
  @override
  void initState() {
    super.initState();
    EventMgr.on(EventType.refreshLogin, (arg) async {
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    EventMgr.off(EventType.refreshLogin);
  }

  @override
  Widget build(BuildContext context) {
    return BasePage(
      title: "账户设置",
      iconType: IconType.back,
      children: [
        header(),
        ListItem(
            texts: "账户安全",
            ontap: () {
              var route = Get.routing.route;

              print('route ===== $route');

              AppData.isLogin ? Get.toNamed(Routes.accountSafe) : Get.toNamed(Routes.login);
            }),
        ListItem(texts: "实名认证", ontap: () => {AppData.isLogin ? Get.toNamed(Routes.userAuth) : Get.toNamed(Routes.login)}),
        ListItem(texts: "服务条款", ontap: () => {Get.toNamed(Routes.statement, arguments: RichTextLinkType.serviceTerm)}),
        ListItem(texts: "隐私设置", ontap: () => {Get.toNamed(Routes.privacySetting)}),
        ListItem(texts: "隐私政策", ontap: () => {Get.toNamed(Routes.statement, arguments: RichTextLinkType.privacyPolicy)}),
        // ListItem(
        //     texts: "微信绑定用户", ontap: () => {Get.toNamed(Routes.bindWechat)}),
        ListItem(texts: "个人信息收集清单", ontap: () => {AppData.isLogin ? Get.toNamed(Routes.statement, arguments: RichTextLinkType.userMsgList) : Get.toNamed(Routes.login)}),
        ListItem(texts: "第三方共享个人清单", ontap: () => {AppData.isLogin ? Get.toNamed(Routes.statement, arguments: RichTextLinkType.shareList) : Get.toNamed(Routes.login)}),
        ListItem(texts: "关于我们", ontap: () => {Get.toNamed(Routes.statement, arguments: RichTextLinkType.aboutUs)}),
        ListItem(texts: "清除缓存", ontap: () => {_showClearCacheDialog(context)}),
        // ListItem(
        //     texts: "账户注销", ontap: () => {Get.toNamed(Routes.destory_account)}),
        AppData.tokenValue == '' ? emptyWidget() : _loginOut(context)
      ],
    );
  }

  //新头部
  Widget header() {
    return Container(
      margin: EdgeInsets.only(bottom: 10.w),
      color: Colors.white,
      padding: EdgeInsets.only(left: 8.w, right: 15.w, bottom: 10.w),
      child: BaseInteractive(
        onClick: () {
          AppData.isLogin ? Get.toNamed(Routes.userInfo) : Get.toNamed(Routes.login);
        },
        childWidget: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              children: [
                BaseImage(
                  url: AppData.avatar == '' ? "default_avatar.png" : AppData.avatar!,
                  width: 55.w,
                  height: 55.w,
                  borderRadius: BorderRadius.circular(55.w / 2),
                ),
                SizedBox(width: 10.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(AppData.nickname!, style: const TextStyle(fontSize: 14.0, color: Color.fromRGBO(0, 0, 0, 0.90), fontWeight: FontWeight.w400)),
                    Text(
                      AppData.phoneNumber!.isNotEmpty ? "账户名:${AppData.phoneNumber!}" : '',
                      style: const TextStyle(fontSize: 14.0, color: Color.fromRGBO(153, 153, 153, 1), fontWeight: FontWeight.w400),
                    )
                  ],
                )
              ],
            ),
            //右侧按钮
            const Icon(
              Icons.arrow_forward_ios,
              size: 14,
              color: Color.fromRGBO(0, 0, 0, 0.30),
              weight: 700,
            )
          ],
        ),
      ),
    );
  }

  /**
  * 按钮
  */
  Widget _loginOut(BuildContext context) => Positioned(
      key: GlobalKey(debugLabel: 'Positioned'),
      bottom: MediaQuery.of(context).padding.bottom,
      child: Container(
          color: Colors.white,
          margin: EdgeInsets.only(top: 15.w),
          padding: EdgeInsets.fromLTRB(18.w, 10.w, 18.w, 10.w),
          child: solidButton("退出登录", () {
            Tools.showModal(
              content: "确认要退出么当前账号么?",
              onCancel: (tag) {},
              onConfirm: (tag) {
                AppData.sid = AppData.sid;
                AppData.uid = '';
                AppData.tokenName = '';
                AppData.tokenValue = '';
                AppData.avatar = "default_avatar.png";
                AppData.nickname = "请登录";
                AppData.phoneNumber = "";
                AppData.isLogin = false;
                Tools.showToast("已退出");
                UmengCommonSdk.onProfileSignOff();
                Get.back();
                EventMgr.send(EventType.refreshLogin);
                EventMgr.send(EventType.refreshLogout);
                EventMgr.send(EventType.refreshCar);

                final homeController = Get.find<HomeController>();
                homeController.isLogin = false;
                homeController.update();

                final bagsController = Get.find<BagsController>();
                bagsController.onPageRefresh();
                bagsController.update();
              },
            );
          })));

  // 显示 iOS 风格弹窗
  Future<void> _showClearCacheDialog(BuildContext context) async {
    await clearAllCache(); // 执行清理缓存逻辑
    showCupertinoDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: const Text("提示"),
          content: const Text("缓存已清理完成！"),
          actions: [
            CupertinoDialogAction(
              child: const Text("确定"),
              onPressed: () {
                Navigator.of(context).pop(); // 关闭弹窗
              },
            ),
          ],
        );
      },
    );
  }

  // 清理缓存逻辑
  Future<void> clearAllCache() async {
    try {
      // 清除临时文件
      final tempDir = await getTemporaryDirectory();
      if (tempDir.existsSync()) {
        tempDir.deleteSync(recursive: true);
      }

      // 清除图片缓存
      await DefaultCacheManager().emptyCache();

      // 清除 SharedPreferences
      //final prefs = await SharedPreferences.getInstance();
      //await prefs.clear();

      print('All caches cleared!');
    } catch (e) {
      print('Error clearing cache: $e');
    }
  }
}
